package com.hanliy.controller;

import com.hanliy.Service.EsService;
import com.hanliy.commom.CommonPage;
import com.hanliy.commom.CommonResult;
import com.hanliy.es.document.EsProduct;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author hanyulin
 * @apiNote
 * @date 2021/11/24 14:44
 */
@RestController
@Api(tags = "ES相关")
@RequestMapping(value = "/search")
public class EsController {

    @Resource
    private EsService esService;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @PostMapping
    public CommonResult save(@RequestBody EsProduct product){
        esService.save(product);
        return CommonResult.success("插入成功");
    }

    @GetMapping(value = "/saveAll")
    public CommonResult saveAll(){
        esService.saveAll();
        return CommonResult.success("插入成功");
    }

    @DeleteMapping(value = "/{ids}")
    public CommonResult delete(@PathVariable("ids") List<Long> ids){
        esService.deleteByIds(ids);
        return CommonResult.success("删除成功");
    }

    @PutMapping
    @ApiOperation(value = "修改")
    public CommonResult<EsProduct> updateById(@RequestBody EsProduct product){
        EsProduct updateProduct = esService.update(product);
        return CommonResult.success(updateProduct);
    }

    @GetMapping("/{id}")
    public CommonResult<Optional<EsProduct>> findProductById(@PathVariable("id") Long id){
        return CommonResult.success(esService.findProductById(id));
    }

    @GetMapping(value = "/findAll")
    public CommonResult<CommonPage<EsProduct>> findAll(
            @RequestParam(required = false, defaultValue = "0") Integer pageNum,
            @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        Page<EsProduct> products = esService.findAll(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(products));
    }


    @GetMapping(value = "/keyword")
    public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = true) String keyword,
                                                      @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                                                      @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        Page<EsProduct> esProductPage = esService.search(keyword, pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(esProductPage));
    }
}
